<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';
import {
  Form,
  FormItem,
  Input,
  InputNumber,
  DatePicker,
  Select,
} from 'ant-design-vue';
import { useBeforeCloseDiff } from '#/utils/popup';
import type {
  VisitConfigForm,
  PlanConfigVO,
} from '#/api/healthPlan/config/planConfig/model';
import {
  planConfigInfo,
  planConfigUpdate,
} from '#/api/healthPlan/config/planConfig';
import type { ManageVO } from '#/api/survey/manage/model';
import { surveyListAll } from '#/api/survey/manage';

const emit = defineEmits<{ reload: [] }>();

const title = '随访方案配置';
const taskData = ref<PlanConfigVO | null>(null);

// 定义表单的默认值，字段与后端Vo对应
const getDefaultValues = (): VisitConfigForm => ({
  reminderName: undefined,
  validityDays: 3,
  surveyKey: undefined,
  triggerType: 'RELATIVE_TO_CYCLE',
  daysAfter: undefined,
});

const formData = ref<VisitConfigForm>(getDefaultValues());

const formRules = ref<Partial<Record<keyof VisitConfigForm, RuleObject[]>>>({
  reminderName: [{ required: true, message: '请输入随访名称' }],
  validityDays: [{ required: true, message: '请输入随访有效期' }],
  surveyKey: [{ required: true, message: '请选择随访量表' }],
  daysAfter: [{ required: true, message: $t('ui.formRules.required') }],
});

const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

const surveyList = ref<ManageVO[]>([]);
// 获取随访量表列表
const getSurveyList = async () => {
  surveyList.value = await surveyListAll();
};

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: () => JSON.stringify(formData.value),
    currentGetter: () => JSON.stringify(formData.value),
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[600px]',
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) return;
    Promise.all([getSurveyList()]);
    modalApi.modalLoading(true);
    const record = modalApi.getData() as PlanConfigVO;
    taskData.value = await planConfigInfo(record.id);
    if (taskData.value && taskData.value.taskConfig) {
      formData.value = { ...getDefaultValues(), ...taskData.value.taskConfig };
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    const data = cloneDeep(formData.value);
    const dataToSubmit = {
      ...taskData.value,
      taskConfig: data,
      // 触发时间配置
      triggerConfig: {
        daysAfter: data.daysAfter,
      },
    };
    await planConfigUpdate(dataToSubmit);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

function handleClosed() {
  resetFields();
  formData.value = getDefaultValues();
  resetInitialized();
}
</script>

<template>
  <BasicModal :title="title">
    <Form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <FormItem label="随访名称" v-bind="validateInfos.reminderName">
        <Input
          v-model:value="formData.reminderName"
          placeholder="请输入随访名称"
        />
      </FormItem>
      <FormItem label="提醒日期" v-bind="validateInfos.daysAfter">
        <InputNumber
          :placeholder="$t('ui.formRules.required')"
          v-model:value="formData.daysAfter"
          addon-before="周期内第"
          addon-after="天"
          :min="1"
        ></InputNumber>
      </FormItem>
      <FormItem label="随访有效期" v-bind="validateInfos.validityDays">
        <InputNumber
          v-model:value="formData.validityDays"
          :min="1"
          addon-after="天"
        />
      </FormItem>
      <FormItem label="随访量表" v-bind="validateInfos.surveyKey">
        <Select
          v-model:value="formData.surveyKey"
          placeholder="请选择（带搜索）"
          :options="surveyList"
          :field-names="{
            label: 'name',
            value: 'key',
          }"
          show-search
        />
      </FormItem>
    </Form>
  </BasicModal>
</template>
